package com.sleepapp.service.impl;

import cn.hutool.core.bean.BeanUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.sleepapp.dto.exception.CustomizeException;
import com.sleepapp.entity.User;
import com.sleepapp.dao.UserDao;
import com.sleepapp.service.UserService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.sleepapp.utils.ResCode;
import com.sleepapp.utils.StpAdminUtil;
import com.sleepapp.utils.StpUserUtil;
import com.sleepapp.vo.LoginBodyVo;
import com.sleepapp.vo.LoginUserResultVo;
import com.sleepapp.vo.UserQueryVo;
import org.springframework.stereotype.Service;

import java.util.List;

/**
 * <p>
 * 用户表 服务实现类
 * </p>
 *
 * @author 
 * @since 2025-03-13
 */
@Service
public class UserServiceImpl extends ServiceImpl<UserDao, User> implements UserService {

    @Override
    public LoginUserResultVo login(LoginBodyVo loginBodyVo) {
        LambdaQueryWrapper<User> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(User::getUsername, loginBodyVo.getUsername())
                .eq(User::getPassword, loginBodyVo.getPassword())
                .eq(User::getRole, "USER");
        User user = getOne(queryWrapper);

        if (user == null) {
            throw new CustomizeException(ResCode.USERNAME_OR_PASSWORD_ERROR);
        }

        StpUserUtil.login(user.getId());
        String tokenValue = StpUserUtil.getTokenValue();
        LoginUserResultVo result = new LoginUserResultVo();
        result.setToken(tokenValue);
        return result;
    }

    @Override
    public LoginUserResultVo adminLogin(LoginBodyVo loginBodyVo) {
        LambdaQueryWrapper<User> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(User::getUsername, loginBodyVo.getUsername())
                .eq(User::getPassword, loginBodyVo.getPassword())
                .eq(User::getRole, "ADMIN");
        User user = getOne(queryWrapper);

        if (user == null) {
            throw new CustomizeException(ResCode.USERNAME_OR_PASSWORD_ERROR);
        }

        StpAdminUtil.login(user.getId());
        String tokenValue = StpAdminUtil.getTokenValue();
        LoginUserResultVo result = new LoginUserResultVo();
        result.setToken(tokenValue);
        return result;
    }

    @Override
    public Integer getPoints() {
        User user = getById(StpUserUtil.getLoginIdAsLong());
        if (user != null) {
            return user.getPoints();
        }
        return 0;
    }

    @Override
    public List<UserQueryVo> userList() {
        LambdaQueryWrapper<User> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(User::getRole, "USER");
        return BeanUtil.copyToList(list(queryWrapper), UserQueryVo.class);
    }
}
